import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'comment/bezier3_painter.dart';
import 'comment/coordinate_painter.dart';
import 'comment/touch_info.dart';

class Bezier3Page extends StatefulWidget {
  @override
  _Bezier3PageState createState() => _Bezier3PageState();
}

class _Bezier3PageState extends State<Bezier3Page> {
  final TouchInfo touchInfo = TouchInfo();

  @override
  void dispose() {
    touchInfo.dispose();
    super.dispose();
    //横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    //全屏显示
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.edgeToEdge,
      overlays: [SystemUiOverlay.top],
    );
  }

  @override
  Widget build(BuildContext context) {
    //横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    //全屏显示
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    return Container(
      color: Colors.white,
      child: Stack(
        fit: StackFit.expand,
        children: [
          CustomPaint(
            painter: CoordinatePainter(),
          ),
          GestureDetector(
            onPanDown: _onPanDown,
            onPanUpdate: _onPanUpdate,
            child: CustomPaint(
              painter: Beziier3Painter(repaint: touchInfo),
            ),
          ),
        ],
      ),
    );
  }

  void _onPanDown(DragDownDetails details) {
    if (touchInfo.points.length < 4) {
      touchInfo.addPoint(details.localPosition);
    } else {
      judgeZone(details.localPosition);
    }
  }

  void _onPanUpdate(DragUpdateDetails details) {
    judgeZone(details.localPosition, update: true);
  }

  ///判断出是否在某点的半径为r圆范围内
  bool judgeCircleArea(Offset src, Offset dst, double r) =>
      (src - dst).distanceSquared <= r * r;

  //判断哪个点被选中
  void judgeZone(Offset src, {bool update = false}) {
    if (update && touchInfo.points.length > 0 && touchInfo.selectIndex != -1) {
      touchInfo.updatePoint(touchInfo.selectIndex, src);
    } else {
      for (int i = 0; i < touchInfo.points.length; i++) {
        if (judgeCircleArea(src, touchInfo.points[i], 15)) {
          touchInfo.selectIndex = i;
          break;
        }
      }
    }
  }
}
